package edu.sctu.yueding.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.activitys.UploadNewsActivity;
import edu.sctu.yueding.adapter.CommunityListViewAdapter;
import edu.sctu.yueding.bean.CommuntiyBean;
import edu.sctu.yueding.bean.CommuntiyData;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.Tweets;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.DateUtils;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.PermissionUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.view.XListView;

import static com.tencent.open.utils.Global.getPackageName;
import static com.umeng.socialize.Config.dialog;


/**
 * Created by Administrator on 2016/8/1.
 */
public class CommunityFragment extends Fragment implements XListView.IXListViewListener {
    private View view;
    private XListView listView;
    private ImageView addTrend;
    private Activity mActivity;
    private RelativeLayout mProgressBarRel;
//    private JsonBaseBeen<CommuntiyData> tweetsJsonBaseBeen = null;

    private CommuntiyBean communtiyBean;

    private int page = 0;
    private List<Tweets> datas = new ArrayList<>();
    private CommunityListViewAdapter adapter = null;
    private boolean isAddAll = true;


    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.community_fragment, container, false);
            initView();
        }

        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (datas == null || datas.size() == 0){
            initData();
        }
    }

    private void initView() {

        /**
         * 重置状态 防止第二次进入 数据获取发生误差
         */
        adapter = null;

        mActivity = getActivity();
        mProgressBarRel = (RelativeLayout) view.findViewById(R.id.id_collection_progress_bar);
        listView = (XListView) view.findViewById(R.id.community_fragment_listView);

        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);

        addTrend = (ImageView) view.findViewById(R.id.community_fragment_addTrend);

        addTrend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求

//                        PermissionUtil.showDialogTipUserRequestPermission(mActivity, permissions);
                        ActivityCompat.requestPermissions(mActivity, permissions, 321);

                    } else {
                        JumpUtils.isLoginJump(getActivity(), UploadNewsActivity.class);
                    }

                } else {
                    JumpUtils.isLoginJump(getActivity(), UploadNewsActivity.class);
                }

            }
        });

        if (communtiyBean == null) {
            initData();
        } else {
            mProgressBarRel.setVisibility(View.GONE);
//            adapter.fresh(datas, isAddAll);
        }

    }


    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        PermissionUtil.showDialogTipUserGoToAppSettting(mActivity);
                    } else {

                    }

                } else {
                    Toast.makeText(mActivity, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PermissionUtil.PERMISSION_TAG) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    PermissionUtil.showDialogTipUserGoToAppSettting(mActivity);
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(mActivity, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    private void initData() {

        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_COMMUNITY + "?page=" + page,
                listener, errorListener, "");
    }

    Response.Listener listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {
            mProgressBarRel.setVisibility(View.GONE);
            Log.d("community json", json);
            page = page + 1;
//            tweetsJsonBaseBeen = JSON.parseObject(json, new TypeReference<JsonBaseBeen<CommuntiyData>>() {
//            }.getType());

            try {
                communtiyBean = JSON.parseObject(json, CommuntiyBean.class);

                datas = communtiyBean.getData().getTweets();
                if (datas != null) {
                    initAdapter();
                }
            } catch (JSONException exception) {
                Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_SHORT).show();
            }
            Log.i("团队", json);
        }
    };
    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Log.d("community json", "error  community   ...");
        }
    };


    @Override
    public void onRefresh() {
        page = 0;
        isAddAll = false;
        initData();

    }

    @Override
    public void onLoadMore() {
        isAddAll = true;
        initData();
    }

    private void initAdapter() {
        if (adapter == null) {
            adapter = new CommunityListViewAdapter(mActivity, datas);
            listView.setAdapter(adapter);
        } else {
            adapter.fresh(datas, isAddAll);
        }

        stop();
    }

    private void stop() {
        listView.stopLoadMore();
        listView.stopRefresh();
        listView.setRefreshTime(DateUtils.getTime());
    }



}
